﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.Domain.Clients;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using T.E.ERP.Write.API.Applicantions.Command.CientsCommand;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.CientsCommandHandler
{
    /// <summary>
    /// 客户档案新增命令处理
    /// </summary>
    public class AddClientHandler : IRequestHandler<AddClientsCommand, APIResult<object>>
    {
        private readonly IBaseRepository<CustomerProfiles> _customerProfiles;
        public readonly IBaseRepository<InvoicingInformation> _invoiceInfos;
        private readonly IBaseRepository<SystemLog> _systemLog;
        private readonly IMapper mapper;

        public AddClientHandler(IBaseRepository<CustomerProfiles> customerProfiles, IMapper mapper, IBaseRepository<InvoicingInformation> invoiceInfos, IBaseRepository<SystemLog> systemLog)
        {
            _customerProfiles = customerProfiles;
            this.mapper = mapper;
            _invoiceInfos = invoiceInfos;
            _systemLog = systemLog;
        }

        public async Task<APIResult<object>> Handle(AddClientsCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.添加成功;
            result.Msg = APIEnum.添加成功.ToString();
            try
            {
                var entity = mapper.Map<CustomerProfiles>(request);
                entity.IsDelete = false;
                await _customerProfiles.Add(entity);

                //实例化系统日志表
                SystemLog systemlog = new SystemLog();
                systemlog.LoginName = systemlog.LoginName;
                systemlog.LoginTime = DateTime.Now;
                systemlog.Dosomething = "添加了一条客户档案信息";
                await _systemLog.Add(systemlog);

                result.data = entity;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString() + ex.Message;
            }
            return await Task.FromResult(result);
        }
    }
}
